package com.redwood.report.net;

import android.util.Log;

import com.duowan.mobile.netroid.Listener;
import com.duowan.mobile.netroid.NetworkResponse;
import com.duowan.mobile.netroid.ParseError;
import com.duowan.mobile.netroid.Response;
import com.duowan.mobile.netroid.request.JsonRequest;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.redwood.report.entity.ServiceResult;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;

/**
 * Json网络请求
 *
 * @author supeng
 *         Created by  on 2016/9/2 14:57.
 */
public class SpRequest extends JsonRequest<ServiceResult> {
    private Type rspCls;

    public SpRequest(int method, String url, JSONObject jsonRequest, Listener<ServiceResult> listener, Type rspCls) {
        super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener);
        this.rspCls = rspCls;
        Log.i("supeng", "request:url=" + url + "  ||String=" + jsonRequest.toString());
    }

    public SpRequest(String url, JSONObject jsonRequest, Listener<ServiceResult> listener, final Type rspCls) {
        this(jsonRequest == null ? Method.GET : Method.POST, url, jsonRequest, listener, rspCls);
    }

    @Override
    public void cancel() {
        super.cancel();
        setListener(null);
    }

    //此处是异步
    @Override
    protected Response<ServiceResult> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data, response.charset);
            Log.i("supeng", "response:url=" + getUrl() + "  ||String=" + jsonString);
            JSONObject jsonObject = new JSONObject(jsonString);
            Gson gson  = new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create();
            ServiceResult rsp = (ServiceResult) gson.fromJson(jsonObject.toString(),  rspCls);
            return Response.success(rsp, response);
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }

    }
}
